package com.cloudcc.mobile.view.login;

import java.io.File;
import java.util.List;

import org.json.JSONException;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.EventList.ServerUrlEvent;
import com.cloudcc.cloudframe.bus.EventList.ServerUrlOneEvent;
import com.cloudcc.cloudframe.model.ServerUrlModel;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.LoginHistoryAdapter;
import com.cloudcc.mobile.adapter.LoginHistoryAdapter.OnHistoryItemClickListener;
import com.cloudcc.mobile.entity.LoginDBModel;
import com.cloudcc.mobile.manager.PrivateCloudCacheManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.LoginParser;
import com.cloudcc.mobile.presenter.LoginPresenter;
import com.cloudcc.mobile.service.LoginService;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UIUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * 登陆页
 * 
 * @author Administrator
 * 
 */
public class LoginNewActivity extends BaseActivity implements
		OnHistoryItemClickListener {

	@Bind(R.id.login_passswd)
	EditText tvPassword;
	@Bind(R.id.login_name)
	EditText tvUserName;
	@Bind(R.id.group_name)
	EditText etGroupName;
	@Bind(R.id.login_auto)
	CheckBox loginAuto;
	@Bind(R.id.login_remember_psw)
	CheckBox rememberMima;
	@Bind(R.id.login_btn)
	Button loginBtn;
	@Bind(R.id.login_group_img)
	ImageView login_group_img;
	@Bind(R.id.login_user_img)
	ImageView loginuserimg;
	@Bind(R.id.login_key_img)
	ImageView loginkeyimg;
	@Bind(R.id.openDrop)
	ImageView openDrop;// 向下的点击
	
	@Bind(R.id.imageView1)
	ImageView imgLogo;// 用户点击的头像

	private PopupWindow pWindow;

	private LoginPresenter loginPresenter = new LoginPresenter();

	private LoginDBModel mLoginModel;// 登录
	
	
	private DisplayImageOptions logoDisplayImageOptions = new DisplayImageOptions.Builder()  
	.showImageForEmptyUri(R.drawable.cloudcc) 
	.showImageOnFail(R.drawable.cloudcc)
	.resetViewBeforeLoading(false)  // default 
	.cacheInMemory(false)
	.imageScaleType(ImageScaleType.EXACTLY)// default  
	.cacheOnDisc(false)
	.build(); 

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		etGroupName.setText(PrivateCloudCacheManager.getInstance()
				.getGroupName());
		login_group_img.setImageResource(R.drawable.group_image);
		
		initLogo();
		addListener();
		
		fillUI();
	}
	private void initLogo() {
		ImageLoader.getInstance().displayImage("file:///"+getLogoChachePath(),imgLogo,logoDisplayImageOptions);
	}
	private void fillUI() {

		// #1 获得最后一个最近登录的帐号
		mLoginModel = loginPresenter.getLastLogin();
		// #1 判断是否是记住用户名

		if (null != mLoginModel) {// 登录历史不为空 根据 记录判断
			fillLogin();
		} else {
			clearEditText();
		}
		// 清空 缓存数据
		RunTimeManager.getInstance().clearUserCache();
		AsyncClient.getInstance().clear(mContext);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		finish();
		startActivity(intent);
	}

	/**
	 * 根据 用户名以及 加密后的密码 转换
	 * 
	 * @param userName
	 * @param encryptPassword
	 *            加密后的密码
	 */
	private void fillLogin() {

		if (mLoginModel == null) {
			return;
		}
		rememberMima.setChecked(mLoginModel.isRememberUser);
		loginAuto.setChecked(mLoginModel.isAutoLogin);
		tvUserName.setText(mLoginModel.userName);
		
		//密码
		String passwordForLogin = mLoginModel.getDecrypt();
		tvPassword.setText(StringUtils.isBlank(passwordForLogin)
				|| (!mLoginModel.isRememberUser) ? StringUtils.EMPTY
				: passwordForLogin);
	}

	private void addListener() {
		// 输入框输入监听
		tvUserName.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				tvPassword.setText("");
				if (Tools.isNull(s.toString())) {
					loginuserimg.setImageResource(R.drawable.login_user);
				} else {
					loginuserimg
							.setImageResource(R.drawable.login_user_hightlighted);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		tvPassword.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (Tools.isNull(s.toString())) {
					loginkeyimg.setImageResource(R.drawable.login_key);
				} else {
					loginkeyimg
							.setImageResource(R.drawable.login_key_hightlighted);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	@OnClick(R.id.openDrop)
	public void clickedShowHistory() {
		List<LoginDBModel> allLogins = loginPresenter.getAllLogins();
		if (ListUtils.isEmpty(allLogins)) {
			Tools.showInfo(mContext, "暂无记录!");
			return;
		}
		showHistory(allLogins);

	}

	private void showHistory(List<LoginDBModel> history) {
		dismissHistory();

		View contentView = LayoutInflater.from(mContext).inflate(
				R.layout.login_popp, null);
		ListView lvHistory = (ListView) contentView.findViewById(R.id.listview);

		LoginHistoryAdapter historyAdapter = new LoginHistoryAdapter(mContext);
		historyAdapter.addData(history);
		historyAdapter.setOnClickListener(this);

		lvHistory.setAdapter(historyAdapter);
		lvHistory.setDividerHeight(0);
		pWindow = new PopupWindow(contentView, tvUserName.getWidth(),
				LayoutParams.WRAP_CONTENT);
		pWindow.setFocusable(true);
		pWindow.setOutsideTouchable(true);
		pWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
		pWindow.showAsDropDown(tvUserName);
	}

	private void dismissHistory() {
		if (pWindow != null) {
			pWindow.dismiss();
			pWindow = null;
		}
	}

	@OnClick(R.id.login_btn)
	public void btnLogin() {
		showWainting("正在登录...");
		loginPresenter.getAppUrlByGroupName(etGroupName.getText().toString().trim());
	}

	/**
	 * 获取应用登录 url
	 * 
	 * @param event
	 */
	public void onEventMainThread(ServerUrlEvent event) {
		if (event.isError()) {
			dismissWainting();
			Tools.showInfo(mContext, "亲，用户名或密码错误，重试一下吧~~");
			return;
		}
		String url = event.getData().data.url;
		UrlTools.url = url + "/";
		UrlManager.APP_UR = url;
		UrlTools.weixinUrl = url;
		loginPresenter.login(tvUserName.getText().toString().trim(), tvPassword
				.getText().toString().trim());
	}
	public void onEventMainThread(ServerUrlOneEvent event) {
		if (event.isError()) {
			dismissWainting();
			showToast(event.getMessage());
			return;
		}
		String url = event.getData().url;
		UrlTools.url = url + "/";
		UrlManager.APP_UR = url;
		UrlTools.weixinUrl = url;
		PrivateCloudCacheManager.getInstance().setGroupName(
				etGroupName.getText().toString());
		loginPresenter.login(tvUserName.getText().toString().trim(), tvPassword
				.getText().toString().trim());
		refreshLogo();
	}

	/**
	 * 登录数据返回
	 * 
	 * @param event
	 */
	public void onEventMainThread(LoginEvent event) {
		dismissWainting();
		if (event.isError()) {
			Tools.showInfo(mContext, "亲，用户名或密码错误，重试一下吧~~");
			return;
		}
		// 当前 密码是 解密后的密码
		String encryptPassword = LoginDBModel.encryptPassword(tvPassword.getText().toString());
		if (mLoginModel!=null&&StringUtils.isNotBlank(mLoginModel.getPasswordEncrypt())) {// 将用户名密码保存到db中记录
			loginPresenter.saveLoginToHistory(tvUserName.getText().toString()
					.trim(),encryptPassword, false, loginAuto.isChecked(),
					rememberMima.isChecked());
		}
		RunTimeManager.setAppBinding(event.getData().binding);
		UserModel user = event.getData().userInfo;
		UserManager.getManager().saveUser(user);
		enterAPP();
	}

	/**
	 * 进入app
	 */
	private void enterAPP() {
		AppContext.isFenXiang = false;
		UIUtils.enterMainUI(mContext);
		finish();
	}

	@Override
	public void onSelectedLogin(LoginDBModel t, int position) {
		dismissHistory();
		mLoginModel = t;
		fillLogin();
	}

	@Override
	public void onClickDeleteLogin(LoginDBModel t, int position) {
		dismissHistory();
		if (tvUserName != null
				&& TextUtils
						.equals(t.userName, tvUserName.getText().toString())) {
			clearEditText();
		}
		loginPresenter.delLogin(t.userName);
	}

	private void clearEditText() {
		tvPassword.setText("");
		tvUserName.setText("");
	}

	@Override
	public int getLayoutId() {
		return R.layout.activity_login2;
	}
	/**
	 * 根据当前的 url获取 logo
	 * 2016-5-5
	 */
	private void refreshLogo(){
		
		//#1 删除 在 指定目录下的图片
		//#2下载图片
		//#3 显示 图片
		
//		new Thread(new Runnable() {
//			//http://app.cloudcc.com/applogos/loginlogo.png
//			@Override
//			public void run() {
//				Bitmap logo = com.cloudcc.mobile.util.ImageUtils.downLoadImg(UrlManager.getManager().getLogoPath());
//				if (logo!=null) {
//					ImageUtils.saveBitmapForPng(getLogoChachePath(), logo, 100);
//				}
//			}
//		}).start();
	}
	
	/** 获得 logo 路径
	 * @return
	 * 2016-5-5
	 */
	private String getLogoChachePath(){
		return mContext.getCacheDir().getAbsolutePath()+File.separator+"logo"+File.separator+"logo.png";
	}
	@Override
	protected boolean hasEventLife() {
		return true;
	}
}
